var InfiniShack = {
	page: 1,
	loading: false,
	loader: $("<div id='infinishack_loader'>Loading more posts...<img src='" + chrome.extension.getURL("loading.gif") + "' alt='Loading...' /></div>"),
	chatty_url: "http://www.shacknews.com/chatty",
	init: function() {
		
		// get chatty
		this.chatty_url = document.location.toString().split("?")[0];
		var pagematch = /\?page=(\d*)/.exec(document.location.search.toString());
		this.page = (pagematch) ? parseInt(pagematch[1]) : 1;
		$(".pagenavigation").eq(1).replaceWith(this.loader);
		$(window).scroll($.proxy(this, "onWindowScroll"));
		// the shack is trying to do clever things to block js requests
		// hopefully this gets around it
		$.ajaxSetup({
			headers: {"X-Requested-With": "YourMom"}
		});
	},
	onWindowScroll: function(e) {
		if(this.loading) return;
		var loader_pos = this.loader.offset().top;
		var window_offset = $(window).scrollTop();
		var window_height = $(window).height();
		if(window_offset + window_height > loader_pos) this.loadMore();
	},
	loadMore: function() {
		console.log("yay!");
		this.page++;
		var holder = $("<div class='infinishack_page' id='infinishack_page_" + this.page + "'></div>");
		var header = $("<div class='infinishack_page_header' id='infinishack_page_" + this.page + "_header'>Page " + this.page + " | <a href='#top'>Top</a></div>");
		this.loader.before(holder);
		holder.before(header);
		this.loading = true;
		holder.load(this.chatty_url + "?page=" + this.page + " .threads", $.proxy(this, "onLoad"));
	},
	onLoad: function(e) {
		this.loading = false;
		$("#infinishack_page_" + this.page + ",#infinishack_page_" + this.page + "_header").show();
	}
	
	
}
InfiniShack.init();
